package org.odk.collect.android.receiver;

import org.json.JSONObject;
import org.odk.collect.android.R;
import org.odk.collect.android.preferences.PreferencesActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class Settings extends BroadcastReceiver {
   public static String ACTION_SETTINGS_SERVER = "org.odk.collect.android.settings.server";
   public static String EXTRA_JSON = "json";

   @Override
   public void onReceive(Context context, Intent intent) {
      if (intent.getAction().equalsIgnoreCase(ACTION_SETTINGS_SERVER)) {
         if (intent.getStringExtra(EXTRA_JSON) != null) {
            //Toast.makeText(context, "Received settings intent " + intent.getStringExtra("json"), Toast.LENGTH_LONG).show();

            // load the settings
            try {
               JSONObject jo = new JSONObject(intent.getStringExtra("json"));
               String url = jo.getString("url");
               String username = jo.getString("username");
               String password = jo.getString("password");

               SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
               if (url != null) settings.edit().putString(PreferencesActivity.KEY_SERVER_URL, url).commit();
               if (username != null) settings.edit().putString(PreferencesActivity.KEY_USERNAME, username).commit();
               if (password != null) settings.edit().putString(PreferencesActivity.KEY_PASSWORD, password).commit();
            } catch (Exception e) {
               Toast.makeText(context, "Invalid ODK server settings received. Ignored.", Toast.LENGTH_LONG).show();
            }

         } else {
            // send back the server setting
            //Toast.makeText(context, "Sending serrver settings", Toast.LENGTH_LONG).show();
         }
      }
   }

}
